package com.lagou.edu.utils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpUtil {

    private final static int FULL_IP_LENGTH = 15;

    public static String getIpAddr(ServletRequest request) {
        HttpServletRequest localRequest = (HttpServletRequest) request;
        String ip = localRequest.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = localRequest.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = localRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.length() > FULL_IP_LENGTH) {
            ip = ip.split(",")[0];
            if (ip.length() > FULL_IP_LENGTH) {
                ip = ip.substring(0, FULL_IP_LENGTH);
            }
        }
        return ip;
    }

    public static String[] getDomainIp(String domain) throws UnknownHostException {
        InetAddress[] array = InetAddress.getAllByName(domain);
        String[] ips = new String[array.length];
        for (int i = 0; i < array.length; i++) {
            ips[i] = array[i].getHostAddress();
        }
        return ips;
    }

    /**
     * 得到本机ip
     */
    public static String getLocalIp() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        //获得本机IP
        return addr.getHostAddress();
    }

}
